<template>
  <div class="modal-overlay">
    <div class="modal">
      <div class="modal-header">
        <h2>用户登录</h2>
        <button class="close-btn" @click="closeModal">×</button>
      </div>
      
      <form @submit.prevent="handleSubmit">
        <div class="form-group">
          <label for="username">用户名</label>
          <input
            type="text"
            id="username"
            v-model="formData.username"
            required
            placeholder="请输入用户名"
          />
          <p class="error" v-if="errors.username">{{ errors.username }}</p>
        </div>
        
        <div class="form-group">
          <label for="password">密码</label>
          <input
            type="password"
            id="password"
            v-model="formData.password"
            required
            placeholder="请输入密码"
          />
          <p class="error" v-if="errors.password">{{ errors.password }}</p>
        </div>
        
        <div class="form-actions">
          <button type="submit" class="btn btn-primary">登录</button>
        </div>
      </form>
      
      <p class="form-footer">
        还没有账号？
        <button class="link-btn" @click="showRegisterModal" >注册</button>
      </p>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useUserStore } from '@/stores/user';
import apiService from '@/services/api';
import md5 from 'js-md5'; 

const store = useUserStore();

const emit = defineEmits(['close', 'login-success','LoginReg']);

const formData = ref({
  username: '23003026',
  password: '123456'
});

const errors = ref({});
const isLoading = ref(false);

const closeModal = () => {
  emit('close');
};

const showRegisterModal = () => {
  
  emit('LoginReg');
};

const handleSubmit = async () => {
  errors.value = {};
  
  if (!formData.value.username) {
    errors.value.username = '用户名不能为空';
    return;
  }
  
  if (!formData.value.password) {
    errors.value.password = '密码不能为空';
    return;
  }
  
  isLoading.value = true;
  
  try {
    const response = await apiService.login({
      username: formData.value.username,
      pwd: md5(formData.value.password)
    });
    
    // 调整为从response.data获取用户数据（根据实际响应结构）
    const token = response.data.token || 'default_token'; // 假设token在data中
    const user = response.data; // 假设data直接是用户对象
    
    store.setToken(token);
    store.setUser(user);
    alert('登录成功')
    emit('login-success');
  } catch (error) {
      try {
    const response = await apiService.login({
      username: formData.value.username,
      pwd: formData.value.password
    });
    
    // 调整为从response.data获取用户数据（根据实际响应结构）
    const token = response.data.token || 'default_token'; // 假设token在data中
    const user = response.data; // 假设data直接是用户对象
    
    store.setToken(token);
    store.setUser(user);
    alert('登录成功')
    emit('login-success');
  } catch (error) {
    
    console.error('登录失败:', error);
    alert("账号或者密码错误")
    if (error.response && error.response.data && error.response.data.message) {
      errors.value.general = error.response.data.message;
    } else {
      errors.value.general = '登录失败，请稍后再试。';
    }
  } finally {
    isLoading.value = false;
  }
    if (error.response && error.response.data && error.response.data.message) {
      errors.value.general = error.response.data.message;
    } else {
      errors.value.general = '登录失败，请稍后再试。';
    }
  } finally {
    isLoading.value = false;
  }
};
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal {
  background-color: white;
  border-radius: 8px;
  width: 100%;
  max-width: 400px;
  padding: 20px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #666;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

.form-group input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
}

.form-group .error {
  color: #e94560;
  font-size: 14px;
  margin-top: 5px;
}

.form-actions {
  margin-top: 20px;
}

.btn {
  padding: 10px 15px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-weight: 500;
  width: 100%;
}

.btn-primary {
  background-color: #e94560;
  color: white;
}

.btn:hover {
  opacity: 0.9;
}

.form-footer {
  margin-top: 20px;
  text-align: center;
  font-size: 14px;
  color: #666;
}

.link-btn {
  background: none;
  border: none;
  color: #e94560;
  cursor: pointer;
  font-weight: 500;
  padding: 0;
}

.link-btn:hover {
  text-decoration: underline;
}
</style>